package com.aps.server.parse.controller.excel;

import com.aps.common.boot.CoreApplicationContext;
import com.aps.common.entity.Result;
import com.aps.server.parse.controller.ExcelRequest;
import com.aps.server.parse.controller.GenericParseController;
import com.aps.server.parse.model.ExcelImportResult;
import com.aps.server.parse.service.ExcelParserService;
import com.aps.server.parse.utils.ExcelParserUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.BeansException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author nbZhuozh
 * @Date 2025-08-29  15:04
 **/
@RestController
@RequestMapping("generic-excel-processing")
public class ExcelParseController implements GenericParseController {

    @Resource
    private ExcelParserService excelParserService;

//    /**
//     * 导入
//     * @param file
//     * @return
//     */
//    @Override
//    @PostMapping("import-file")
//    public Result<Map<String,Object>> importFile(@RequestBody ExcelRequest request ) {
//        Map<String,Object> response = new HashMap<>();
//        try {
//            List<Map<String, Object>> read = read(request.getFile(), "");
//            int size = CollectionUtils.isEmpty(read) ? 0 : read.size();
//            response.put("readSize", size);
//            return Result.success(response,"导入成功");
//        }catch (Exception e) {
//            e.printStackTrace();
//            //TODO error details
//            return Result.error("导入失败");
//        }
//    }

    /**
     * 导入
     * @param file
     * @param targetModelName
     * @return
     */
    @Override
    @PostMapping("import-file-entity")
    public Result<ExcelImportResult> importFile(@RequestParam("file") MultipartFile file ,
                                                    @RequestParam("targetModelName") String targetModelName) {
        if(StringUtils.isEmpty(targetModelName)){
            return Result.error("未识别到对应实体名称");
        }
        Object target ;
        try {
            target = CoreApplicationContext.getApplicationContext().getBean(targetModelName);
            //do
            ExcelImportResult excelImportResult = excelParserService.importFile(file, target.getClass());
//            List<Object> read = read(file, target.getClass());
            Thread.sleep(5000);
            if(StringUtils.isEmpty(excelImportResult.getErrorExcelDetailsMsg())){
                return Result.success(excelImportResult,"导入失败");
            }
            return Result.success(excelImportResult,"导入成功");
        } catch (BeansException beansException) {
            return Result.error("服务器错误，未匹配对应接受实体");
        } catch (IOException e){
            return Result.error("解析excel文件失败");
        } catch (Exception e){
            e.printStackTrace();
            return Result.error("服务异常，导入失败");
        }
    }


    /**
     * 导出模板
     * @param targetModelName
     * @return
     */

    @Override
    @PostMapping("export-template")
    public ResponseEntity<byte[]> exportTemplate(@RequestBody ExcelRequest request) {
        try {
            //验证是否 包含类  或是否为接受的dto
            Class<?> aClass = validateClazz(request.getTargetModelName());
            if(aClass == null){
                return ResponseEntity.notFound().build();
            }
            //write
            byte[] bytes = excelParserService.exportTemplate(aClass, "");
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", ExcelParserUtil.getExcelName(aClass) + ".xlsx");
            return ResponseEntity.ok().headers(headers).body(bytes);

        }catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }


}
